package java8.optional;

import java.util.Optional;

/**
 * @program: util
 * @description:
 * @author: zhouliangliang
 * @create: 2019-09-12 10:40
 **/
public class Main {

    private Insurance insurance;

    public void test() {
        insurance = new Insurance();
        insurance.setName("insurance");
        Optional<Insurance> optInsurance = Optional.ofNullable(insurance);
        optInsurance.map(Insurance::getName).ifPresent((x)-> {
            System.out.println(x);
        });

        //orElse测试
        System.out.println(optInsurance.map(Insurance::getName).orElse("xxxx"));


        //测试filter
        optInsurance.filter( insurance1 -> "".equals(insurance1.getName())).ifPresent(x-> System.out.println("ok"));



    }

    public String getCarInsuranceName(Optional<Person> person) {
        return person.isPresent() ? person.flatMap(Person::getCar).flatMap(Car::getInsurance).map(Insurance::getName).orElse("not exist") : " person is null ";
    }

    public String getCarInsuranceName2(Optional<Person> person, int minAge) {
        String value = person.filter(p -> p.getAge().orElseGet(() -> 5) > minAge)
                .flatMap(Person::getCar)
                .flatMap(Car::getInsurance)
                .map(Insurance::getName)
                .orElse("default");
        System.out.println(value);
        return value;
    }


    public static void main(String[] args) {
        Insurance ins = new Insurance();
        ins.setName("first ins");

        Car car = new Car();
        car.setInsurance(Optional.of(ins));


        Person person = new Person();
//        person.setAge(null);
        person.setCar(Optional.of(car));
        new Main().getCarInsuranceName2(Optional.of(person), 10);
    }

}
